<?php

namespace MzSms\Request;

use MzSms\SmsSdk;
use GuzzleHttp\Client;
use MzSms\Response\Response;
use MzSms\Request\RequestBase;
use GuzzleHttp\Exception\GuzzleException;

class BatchSend extends RequestBase
{
    private array $mobileList = [];
    private int $templateId = 0;
    private array $params = [];

    public function addMobile($mobile): self
    {
        if (!is_string($mobile)) {
            $mobile = (string)$mobile;
        }
        $this->mobileList[] = $mobile;
        return $this;
    }

    public function setTemplateId($templateId): self
    {
        if (!is_numeric($templateId)) {
            throw new \Exception("参数格式不正确", 500);
        }
        if (is_string($templateId)) {
            $templateId = (int)$templateId;
        }
        $this->templateId = $templateId;
        return $this;
    }

    public function addParams(array $params): self
    {
        $this->params[] = $params;
        return $this;
    }

    function __construct(SmsSdk $smsSdk)
    {
        parent::__construct($smsSdk);
        $this->apiPath = "/sdk/batchSend";
    }

    private function checkParams()
    {
        if (empty($this->params)) {
            throw new \Exception("缺少 params 参数", 500);
        }
        if (empty($this->mobileList)) {
            throw new \Exception("缺少 mobile 手机号", 500);
        }
        if (empty($this->templateId)) {
            throw new \Exception("缺少 templateId 模板编号", 500);
        }
    }

    public function request(): Response
    {
        $this->checkParams();
        try {
            $client = new Client();
            $response = $client->post($this->smsSdk->getHost() . $this->apiPath, [
                'timeout' => $this->smsSdk->getTimeout(),
                'headers' => [
                    'app-code' => $this->smsSdk->getAppCode(),
                ],
                'form_params' => [
                    'mobile_list_json' => json_encode($this->mobileList, JSON_UNESCAPED_UNICODE),
                    'template_id' => $this->templateId,
                    'params' => $this->params,
                ],
            ]);
            return new Response($response->getBody()->getContents());
        } catch (GuzzleException $e) {
            throw $e;
        }
    }
}
